<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="main" class="name1 name2 name3"></div>
    <script>

        /**
         * classList是集合DOMTokenList的实例, 也可以通过item()获取某一项
         * 
         * DOMTokenList还增加了如下方法:
         * 1、add(value)
         * 2、contains(value)
         * 3、remove(value)
         * 4、toggle(value)
        */

        const main = document.getElementById("main")
        console.log(main.classList) // DOMTokenList(3)

        // 添加类name4
        main.classList.add('name4')
        console.log(main.classList)

        // 删除类name2
        main.classList.remove('name2')
        console.log(main.classList)

        // 判断name3这个class是否存在
        const res = main.classList.contains('name3')
        console.log(res) // true

        // toggle如果已经存在name3则删除，否则添加
        main.classList.toggle('name3')
        console.log(main.classList)

        main.classList.toggle('name3')
        console.log(main.classList)

        // 迭代类名
        for (let classitem of main.classList) {
            console.log(classitem)
        }

    </script>
</body>
</html>